package com.WebMentorPro.system.controller;

import com.WebMentorPro.system.annotation.AuthCheck;
import com.WebMentorPro.system.common.BaseResponse;
import com.WebMentorPro.system.common.DeleteRequest;
import com.WebMentorPro.system.common.ErrorCode;
import com.WebMentorPro.system.common.ResultUtils;
import com.WebMentorPro.system.constant.UserConstant;
import com.WebMentorPro.system.exception.BusinessException;
import com.WebMentorPro.system.exception.ThrowUtils;
import com.WebMentorPro.system.model.dto.meeting.MeetingAddRequest;
import com.WebMentorPro.system.model.dto.meeting.MeetingQueryByTeacherRequest;
import com.WebMentorPro.system.model.dto.meeting.MeetingQueryRequest;
import com.WebMentorPro.system.model.dto.meeting.MeetingUpdateRequest;
import com.WebMentorPro.system.model.entity.Meeting;
import com.WebMentorPro.system.model.entity.Teacher;
import com.WebMentorPro.system.model.entity.User;
import com.WebMentorPro.system.model.vo.LoginUserVO;
import com.WebMentorPro.system.model.vo.MeetingVO;
import com.WebMentorPro.system.service.MeetingService;
import com.WebMentorPro.system.service.TeacherService;
import com.WebMentorPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 开会接口
 *
 * @author bianxinyao
 */
@RestController
@RequestMapping("/meeting")
@Slf4j
@Api(tags = {"开会接口"})
public class MeetingController {

    @Resource
    private UserService userService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private MeetingService meetingService;

    // region 登录相关

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 获取当前登录异科导师
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login/teacher")
    @ApiOperation(value = "获取当前登录异科导师")
    public BaseResponse<Teacher> getLoginTeacher(HttpServletRequest request) {
        Teacher teacher = teacherService.getLoginTeacher(request);
        return ResultUtils.success(teacher);
    }

    // endregion

    // region 增删改查

    /**
     * 创建会议
     *
     * @param meetingAddRequest
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建会议")
    public BaseResponse<Long> addAdminNotification(@RequestBody MeetingAddRequest meetingAddRequest, HttpServletRequest request) {
        if (meetingAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = teacherService.getLoginTeacher(request).getId();
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("id", id);
        if (teacherService.getOne(queryWrapper) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "无权限创建会议");
        }
        Meeting meeting = new Meeting();
        BeanUtils.copyProperties(meetingAddRequest, meeting);
        meeting.setTeacherId(Math.toIntExact(id));
        boolean result = meetingService.save(meeting);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "会议创建失败");
        return ResultUtils.success(meeting.getId());
    }

    /**
     * 删除会议
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除会议")
    public BaseResponse<Boolean> deleteNotification(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        boolean result = meetingService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除会议失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新会议
     *
     * @param meetingUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新会议")
    public BaseResponse<Boolean> updateNotification(@RequestBody MeetingUpdateRequest meetingUpdateRequest, HttpServletRequest request) {
        if (meetingUpdateRequest == null || meetingUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Meeting meeting = new Meeting();
        QueryWrapper<Meeting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", meetingUpdateRequest.getId());
        Meeting one = meetingService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "会议不存在");
        }
        // 校验更新通知权限 当登录用户等于发布通知的用户，则更新，则允许更新所有通知
        Teacher currentTeacher = teacherService.getLoginTeacher(request);
        if (currentTeacher == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }

        if (!currentTeacher.getId().equals(one.getTeacherId().longValue())) {
            log.info("用户 " + currentTeacher.getId() + " attempted to update meeting " + one.getTeacherId());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "无权限更新会议");
        }

        if (meetingUpdateRequest.getMeetingTime() == null || meetingUpdateRequest.getMeetingTime().equals("")) {
            meetingUpdateRequest.setMeetingTime(one.getMeetingTime());
        }
        if (meetingUpdateRequest.getMeetingNotes() == null || meetingUpdateRequest.getMeetingNotes().equals("")) {
            meetingUpdateRequest.setMeetingNotes(one.getMeetingNotes());
        }
        if (meetingUpdateRequest.getMeetingAddress() == null || meetingUpdateRequest.getMeetingAddress().equals("")) {
            meetingUpdateRequest.setMeetingAddress(one.getMeetingAddress());
        }
        if (meetingUpdateRequest.getMeetingTopic() == null || meetingUpdateRequest.getMeetingTopic().equals("")) {
            meetingUpdateRequest.setMeetingTopic(one.getMeetingTopic());
        }
        BeanUtils.copyProperties(meetingUpdateRequest, meeting);
        boolean result = meetingService.updateById(meeting);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新会议失败");
        return ResultUtils.success(result);
    }

    /**
     * 分页获取全部会议（仅管理员）
     *
     * @param meetingQueryRequest
     * @return
     */
    @PostMapping("/get/all/admin")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取全部通知（仅管理员）")
    public BaseResponse<Page<MeetingVO>> getMeeting(@RequestBody MeetingQueryRequest meetingQueryRequest) {
        long current = meetingQueryRequest.getCurrent() == 0 ? 1 : meetingQueryRequest.getCurrent();
        long size = meetingQueryRequest.getPageSize() == 0 ? 10 : meetingQueryRequest.getPageSize();

        Page<MeetingVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<MeetingVO> meetingVOPage = meetingService.getQueryWrapper(pageParam, meetingQueryRequest);

        return ResultUtils.success(meetingVOPage);
    }

    /**
     * 异科导师分页获取自己的会议
     *
     * @param meetingQueryByTeacherRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/teacher")
    @ApiOperation(value = "异科导师分页获取自己的会议")
    public BaseResponse<Page<MeetingVO>> getMeetingByTeacher(@RequestBody MeetingQueryByTeacherRequest meetingQueryByTeacherRequest, HttpServletRequest request) {
        String teacherName = teacherService.getLoginTeacher(request).getTeacherName();

        long current = meetingQueryByTeacherRequest.getCurrent() == 0 ? 1 : meetingQueryByTeacherRequest.getCurrent();
        long size = meetingQueryByTeacherRequest.getPageSize() == 0 ? 10 : meetingQueryByTeacherRequest.getPageSize();

        Page<MeetingVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<MeetingVO> meetingVOPage = meetingService.getQueryByTeacher(pageParam, meetingQueryByTeacherRequest, teacherName);

        return ResultUtils.success(meetingVOPage);
    }

    /**
     * 学生分页获取自己参加的会议
     *
     * @param meetingQueryByTeacherRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/student")
    @ApiOperation(value = "学生分页获取自己参加的会议")
    public BaseResponse<Page<MeetingVO>> getMeetingByStudent(@RequestBody MeetingQueryByTeacherRequest meetingQueryByTeacherRequest, HttpServletRequest request) {
        Integer teacherId = userService.getLoginUser(request).getTeacherId();

        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", teacherId);
        Teacher one = teacherService.getOne(queryWrapper);
        String teacherName = one.getTeacherName();
        long current = meetingQueryByTeacherRequest.getCurrent() == 0 ? 1 : meetingQueryByTeacherRequest.getCurrent();
        long size = meetingQueryByTeacherRequest.getPageSize() == 0 ? 10 : meetingQueryByTeacherRequest.getPageSize();

        Page<MeetingVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<MeetingVO> meetingVOPage = meetingService.getQueryByTeacher(pageParam, meetingQueryByTeacherRequest, teacherName);

        return ResultUtils.success(meetingVOPage);
    }

    // endregion
}
